package 合并区间;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class Solution {
    public static void main(String[] args) {
        int[][] ints =  new int[][]{
                {1,3},{2,6},{8,10},{15,18}
//               {1,4},{5,6}
//                 {2,3},{4,6},{5,7},{3,4}
//                {2,3},{4,5},{6,7},{8,9},{1,10}
        };
        int[][] merge = merge(ints);
        for (int[] ints1 : merge) {
            System.out.println(ints1[0] + "," + ints1[1]);
        }
    }

    public static int[][] merge(int[][] intervals) {

        List<List<Integer>> list = new ArrayList<>();

        out: for (int[] interval : intervals) {
            int start = interval[0];
            int end = interval[1];

            if(list.size() == 0){
                list.add(Arrays.asList(start,end));
            }
            else{
                Iterator<List<Integer>> iterator = list.iterator();
                while(iterator.hasNext()){
                    List<Integer> integers = iterator.next();
                    int start1 = integers.get(0);
                    int end1 = integers.get(1);

                    if(start <= start1 && end >= end1){
                        iterator.remove();
                    }
                    else if(start1 <= start && end1 >= end){
                        continue out;
                    }
                    else if(start <= start1 && end >= start1){
//                        integers.set(0,start);
                        end = end1;
                        iterator.remove();

                    }
                    else if(start1 <= start && end1 >= start){
//                        integers.set(1,end);
                        start = start1;
                        iterator.remove();

                    }
                    else if(start <= end1 && end >= end1){
                        integers.set(1,end);
                        start = start1;
                        iterator.remove();

                    }
                    else if(start1 <= end && end1 >= end){
//                        integers.set(0,start);
                        end = end1;
                        iterator.remove();
                    }
                }

                list.add(Arrays.asList(start,end));
            }
        }

        int[][] results = new int[list.size()][2];
        for (int i = 0; i < list.size(); i++) {

            int[] temp = new int[]{list.get(i).get(0),list.get(i).get(1)};
            results[i]=temp;
        }

        return results;
    }


}
